﻿using StandXunYouServer.IRepository;
using StandXunYouServer.IServices;
using StandXunYouServer.Model;
using StandXunYouServer.Utility;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StandXunYouServer.Services
{
    public class AnswerQuestionsServices : IAnswerQuestionsServices
    {
        private readonly IBaseRepository _baseConn;

        public AnswerQuestionsServices(IBaseRepository baseConn)
        {
               _baseConn = baseConn;
        }

        public async Task<IEnumerable<AnswerQuestions>> GetRandomTopicQueryAsync()
        {
            var qList = await _baseConn.QueryAllAsync<AnswerQuestions>("select Top(2)* from AnswerQuestions Order by NEWID()");
            return qList; 
        }

        public async Task<int> UserIsAnswerAsync(string UserId)
        {
            var sql = "select count(1) as count from ReCord where UserId =@userId";
            var result = await _baseConn.GetRecoreCountAsync(sql, new { userId = UserId });
            return result;
        }

        public async Task<int> CorrectAnswerAsync(string[] topicId, string[] topicOption)
        {
            var sql = "select Count(1) from AnswerQuestions where (TopicId = @OneTopicId and Answer = @OneOption) or (TopicId = @TwoTopicId and Answer = @TwoOption)";

            var result = await _baseConn.GetRecoreCountAsync(sql,
                new
                {
                    OneTopicId = topicId[0],
                    TwoTopicId = topicId[1],
                    OneOption = topicOption[0],
                    TwoOption = topicOption[1]
                }
            );
            return result;
        }

        public async Task<bool> UserAddPointsAsync(string userId, int points)
        {
            var sql = "update Users set UserPoints =@Points where Id = @Id";
            var result = await _baseConn.UpdateAsync(sql, new { Points = points, Id = userId });
            return result;
        }

        public async Task<bool> InsertReCordAsync(string userId, string topicNum, int points)
        {
            var gid = Guid.NewGuid(); //生成GUID
            var sql = "insert into ReCord values(@Guid, @UserId, @Points, @TopicNum)";
            var result = await _baseConn.InsertAsync(sql, new { Guid = gid, UserId = userId, Points = points, TopicNum = topicNum });
            return result;
        }

        public async Task<bool> UpdateUserPointsAndInsertReCordTranAsync(string userId, int points, ReCord model)
        {
            var sql = "update Users set UserPoints += @Points where Id =@Id";
            var result = await _baseConn.UpdateAndInserTranAsync(sql, new { Id = userId, Points = points }, model);
            return result;
        }
    }
}
